using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DrawOutline : PostEffectsBase
{
    public Shader drawOccupied;
    public Camera additionalCamera;
    private Camera mainCamera = Camera.main;
    public Shader targetShader;
    public Material targetMaterial;
    public Material occupiedMaterial;
    
    public RenderTexture tempRT;
    public Color outlineColor;
    public int outlineWidth;
    public int iterations;
    public MeshFilter[] meshFilters;
    public GameObject[] targets;
    
    private void Awake()
    {
        additionalCamera.CopyFrom(mainCamera);
        additionalCamera.clearFlags = CameraClearFlags.Color;
        additionalCamera.backgroundColor = Color.black;
        additionalCamera.cullingMask = 1 << LayerMask.NameToLayer("Outline"); // 只渲染"Outline"层的物体
    }

    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        if (targetMaterial != null && drawOccupied != null && additionalCamera != null && targets != null)
        {
            tempRT = RenderTexture.GetTemporary(source.width, source.height, 0);
            additionalCamera.targetTexture = tempRT;

            // 下面这段循环和方法2相同（除了渲染到额外相机）。
            for (int i = 0; i < targets.Length; i++)
            {
                if (targets[i] == null)
                    continue;
                meshFilters = targets[i].GetComponentsInChildren<MeshFilter>();
                for (int j = 0; j < meshFilters.Length; j++)
                    Graphics.DrawMesh(meshFilters[j].sharedMesh, meshFilters[j].transform.localToWorldMatrix, occupiedMaterial, LayerMask.NameToLayer("PostEffect"), additionalCamera); // 描绘选中物体的所占面积
            }
            additionalCamera.Render();  // 需要调用渲染函数，才能及时把描绘物体渲染到纹理中

            targetMaterial.SetTexture("_SceneTex", source);
            targetMaterial.SetColor("_Color", outlineColor);
            targetMaterial.SetInt("_Width", outlineWidth);
            targetMaterial.SetInt("_Iterations", iterations);

            // 使用描边混合材质实现描边效果
            Graphics.Blit(tempRT, destination, targetMaterial);

            tempRT.Release();
        }
        else
            Graphics.Blit(source, destination);
    }
    
}
